package org.raymond.icloud.modules.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.raymond.icloud.apis.admin.entity.TRolePermissionRel;
import org.raymond.icloud.apis.admin.entity.TSysPermission;
import org.raymond.icloud.apis.admin.entity.enums.StateEnum;
import org.raymond.icloud.modules.admin.mapper.TSysPermissionMapper;
import org.raymond.icloud.modules.admin.service.ITRolePermissionRelService;
import org.raymond.icloud.modules.admin.service.ITSysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
@Service
public class TSysPermissionServiceImpl extends ServiceImpl<TSysPermissionMapper, TSysPermission> implements ITSysPermissionService {
    @Autowired
    private ITRolePermissionRelService itRolePermissionRelService;

    @Override
    public List<TSysPermission> getsAssociatedPermissionByRoleIds(Set<Long> roleIds) {
        if(CollectionUtil.isEmpty(roleIds)) {
            return null;
        }
        LambdaQueryWrapper<TRolePermissionRel> listRelWrapper = new LambdaQueryWrapper<>();
        listRelWrapper.select(TRolePermissionRel::getRoleId, TRolePermissionRel::getPermissionId);
        listRelWrapper.in(TRolePermissionRel::getRoleId, roleIds);
        List<TRolePermissionRel> rolePermissionRels = itRolePermissionRelService.list(listRelWrapper);
        if(CollectionUtil.isEmpty(rolePermissionRels)) {
            return null;
        }
        Set<Long> directPermissionIdSet = rolePermissionRels.stream().mapToLong(TRolePermissionRel::getPermissionId).boxed().collect(Collectors.toSet());
        LambdaQueryWrapper<TSysPermission> listDirectPermissionWrapper = new LambdaQueryWrapper<>();
        listDirectPermissionWrapper.in(TSysPermission::getId, directPermissionIdSet);
        listDirectPermissionWrapper.eq(TSysPermission::getState, StateEnum.NORMAL);
        List<TSysPermission> directPermissionList = list(listDirectPermissionWrapper);
        if(CollectionUtil.isEmpty(directPermissionList)) {
            return null;
        }
        return directPermissionList;
    }
}
